<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="故障设备" prop="productId">
        <Dialog @dialogChange="queryParams.productId = $event.value" :echoValue="queryParams.productName"
          parameter="rows" ref="productIdDialog" value="id" label="name" search="code/name" url="/basic/eqpInfo/list"
          :column="['设备编号/code', '设备名称/name']" placeholder="请选择内容" />
      </el-form-item>
      <el-form-item label="故障类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择故障类型" clearable size="small">
          <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属工厂" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择所属工厂" clearable size="small"
          @keyup.enter.native="handleQuery">
          <el-option v-for="dept in deptOptions" :key="dept.deptId" :label="dept.name" :value="dept.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="故障时间">
        <el-date-picker :editable="false" v-model="daterangeFaultTime" size="small" style="width: 240px"
          value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <!--      <el-form-item label="上报人" prop="reportUserId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.reportUserId"-->
      <!--          placeholder="请输入上报人"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['equipment:manualRepairFiles:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['equipment:manualRepairFiles:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['equipment:manualRepairFiles:remove']">删除</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['equipment:manualRepairFiles:export']"-->
      <!--          >导出</el-button-->
      <!--        >-->
      <!--      </el-col>-->
      <!--      <right-toolbar-->
      <!--        :showSearch.sync="showSearch"-->
      <!--        @queryTable="getList"-->
      <!--      ></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="repairFilesList" @selection-change="handleSelectionChange" max-height="550">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="故障设备" align="center" prop="productName" />
      <el-table-column label="故障类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="所属工厂" align="center" prop="dept.deptName" />
      <el-table-column label="故障时间" align="center" prop="faultTime" width="180">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.faultTime, "{y}-{m}-{d} {h}:{i}")
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="故障状态" align="center" prop="statusStr"  />
      <el-table-column label="上报人" align="center" prop="user.nickName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleApproval(scope.row)"
            v-hasPermi="['equipment:manualRepairFiles:edit']" v-if="scope.row.status == '05'||scope.row.status == '03'">审批</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:manualRepairFiles:edit']" v-if="scope.row.status != '06'">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:manualRepairFiles:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改故障管理信息对话框 -->
    <el-dialog fullscreen :title="title" :visible.sync="open" width="900px" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-col :span="24">
              <el-form-item label="所属工厂" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择所属工厂" clearable size="small" :disabled="openDisabled">
                  <el-option v-for="dept in deptOptions" :key="dept.deptId" :label="dept.name" :value="dept.deptId" />
                </el-select>
                <!--                <el-input v-model="form.deptId" placeholder="请输入所属工厂" />-->
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="故障设备" prop="productId">
                <Dialog @dialogChange="form.productId = $event.value" :echoValue="form.productName" parameter="rows"
                  value="id" label="name" search="code/name" url="/basic/eqpInfo/list"
                  :column="['设备编号/code', '设备名称/name']" :openDisabled="openDisabled" placeholder="请选择内容" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="故障位置" prop="address">
                <el-input v-model="form.address" placeholder="请输入故障位置" :disabled="openDisabled" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="故障类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择故障类型" :disabled="openDisabled">
                  <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="故障时间" prop="faultTime">
                <el-date-picker :editable="false" clearable size="small" v-model="form.faultTime" type="datetime"
                  value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" placeholder="选择故障时间"
                  :disabled="openDisabled">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12" v-show="form.type == '01'">-->
            <!--              <el-form-item label="停机记录" prop="stopInfoId">-->
            <!--                <el-input-->
            <!--                  v-model="form.stopInfoId"-->
            <!--                  placeholder="请输入停机记录"-->
            <!--                  :disabled="openDisabled"-->
            <!--                />-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->

            <el-col :span="24">
              <el-form-item label="故障描述" prop="faultContent">
                <el-input v-model="form.faultContent" type="textarea" :rows="3" placeholder="请输入内容"
                  :disabled="openDisabled" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12"> -->
            <!-- <el-form-item label="处理人" prop="userName"> -->
            <!--                <el-input-->
            <!--                  :disabled="openDisabled"-->
            <!--                  v-model="form.userName"-->
            <!--                  placeholder="请选择维修人员"  @click.native="$dialog.utils.openDialog($refs.Dialog)"-->
            <!--                />-->
            <!--                <UserDialog @dialogChange="dialogChange" ref="Dialog" :selection="false" />-->
            <!-- <el-input v-if="form.user" v-model="form.user.nickName" :disabled="openDisabled" /> -->
            <!-- </el-form-item> -->
            <!-- </el-col> -->
            <el-col :span="24">
              <el-form-item label="故障级别" prop="type">
                <el-select v-model="form.repairLevel" placeholder="请选择故障类型" :disabled="openDisabled">
                  <el-option v-for="dict in levelOptions" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="是否需要备件" prop="isSpareParts">
                <el-radio-group v-model="form.isSpareParts" :disabled="openDisabled">
                  <el-radio v-for="dict in isSparePartsStatus" :key="dict.dictValue" :label="dict.dictValue">{{
                    dict.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.isSpareParts == 'Y'">
              <el-form-item label="申请备件记录" prop="outStockIds">
                <el-input v-model="form.outStockNames" :disabled="openDisabled" />
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="故障原因和解决方案" prop="reasonSolution">
                <editor v-model="form.reasonSolution" :min-height="192" :disabled="openDisabled" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预防措施" prop="premeasure">
                <editor v-model="form.premeasure" :min-height="192" :disabled="openDisabled" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.isToCheck != 'Y'">
              <el-form-item label="复核意见" prop="reviewRemark">
                <el-input v-model="form.reviewRemark" type="textarea" placeholder="请输入内容" :disabled="openDisabled" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="验收时间" prop="checkTime">
                <el-date-picker :editable="false" clearable size="small" v-model="form.checkTime" type="datetime"
                  value-format="yyyy-MM-dd HH:mm" :disabled="openDisabled">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="维修时长" prop="repairTime">
                <el-input v-model="form.repairTime" :disabled="openDisabled" />
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="验收意见" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="openDisabled" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="isApproval">
              <el-form-item label="验收结果" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in statusDispatch" :key="dict.dictValue" :label="dict.dictValue">{{
                    dict.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- <el-col :span="6">
            <el-timeline :reverse="reverse">
              <el-timeline-item v-for="(activity, index) in activities" :key="index">
                {{ "[" + activity.nickName + "]" + activity.dealContent }}
              </el-timeline-item>
            </el-timeline>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled||isApproval">
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listRepairFiles,
    getRepairFiles,
    delRepairFiles,
    addRepairFiles,
    updateRepairFiles,
    getRecord,
  } from "@/api/equipment/repairInfo/manualRepairFiles";
  import { delRepairInfo } from "@/api/equipment/repairInfo/repairInfo";
  import { getFactoryList, dateDifference } from "@/api/equipment/common";
  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    name: "ManualRepairFiles",
    components: { Treeselect },
    data() {
      var checkStatus = (rule, value, callback) => {
        if (value != "03" && value != "06") {
          return callback(new Error("请选择验收结果"));
        } else {
          callback();
        }
      };
      return {
        isApproval: false,
        //弹窗是否禁止编辑
        openDisabled: true,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedEqpRepairRecord: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 故障管理信息表格数据
        repairFilesList: null,
        // 故障处理记录表格数据
        eqpRepairRecordList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 故障类型字典
        typeOptions: [],
        // 故障时间时间范围
        daterangeFaultTime: [],
        // 故障状态字典
        statusOptions: [],
        statusDispatch: [
          { dictLabel: "验收通过", dictValue: "06" },
          { dictLabel: "验收未通过", dictValue: "03" },
        ],
        // 故障级别字典
        levelOptions: [],
        // 部门树选项
        deptOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 50,
          address: null,
          type: null,
          deptId: null,
          faultTime: null,
          status: null,
          reportUserId: null,
          productId: null,
          productName: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          status: [{ validator: checkStatus, trigger: "change" }],
        },
        visible: false,
        reverse: true,
        activities: [
          {
            nickName: "",
            dealContent: "",
            dealTime: "",
          },
        ],
        isSparePartsStatus: [],

      };
    },
    created() {
      this.getList();
      // 故障类型字典翻译
      this.getDicts("fault_type").then((response) => {
        this.typeOptions = response.data;
      });
      // 故障状态字典翻译
      this.getDicts("fault_status").then((response) => {
        this.statusOptions = response.data;
      });
      this.getDicts("fault_level").then((response) => {
        this.levelOptions = response.data;
      });
      this.getDicts("sys_yes_no").then((response) => {
        this.isSparePartsStatus = response.data;
      });
      // this.getTreeselect();
      this.getFactory();
    },
    activated() {
      this.acquiesce();
      this.getList();
    },
    methods: {
      /* 查询表单默认赋值 */
      acquiesce() {
        if (this.$route.query.eqpName) {
          this.queryParams.type = this.$route.query.productId;
          // this.queryParams.productName = this.$route.query.eqpName;
          this.daterangeFaultTime = [
            this.$route.query.stopDateStart,
            this.$route.query.stopDateEnd,
          ];

        }
      },
      getactivities(act) {
        if (act.dealStatus == "05" || act.dealStatus == "06") {
          return act.dealTime.substring(0, 10);
        } else {
          return act.dealTime;
        }
      },
      getFactory() {
        getFactoryList().then((response) => {
          this.deptOptions = response.data;
        });
      },
      // /** 查询部门下拉树结构 */
      // getTreeselect() {
      //     treeselect().then((response) => {
      //         this.deptOptions = response.data;
      //     });
      // },
      /** 查询故障管理信息列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeFaultTime && "" != this.daterangeFaultTime) {
          this.queryParams.params["beginFaultTime"] = this.daterangeFaultTime[0];
          this.queryParams.params["endFaultTime"] = this.daterangeFaultTime[1];
        }
        listRepairFiles(this.queryParams).then((response) => {
          for(let item of response.rows){
            if(item.status == '06'){
              item.statusStr='验收通过'
            }else if(item.status == '05'){
              item.statusStr='待验收'
            }else{
              item.statusStr='验收驳回'
            }
          }
          this.repairFilesList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 故障类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.type);
      },
      // 故障状态字典翻译
      statusFormat(row, column) {
        let status = '验收通过'
        // console.log(row.status)
        if (row.status != '06') {
          status = '待验收';
        }
        return status
        // return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          productId: null,
          productName: null,
          address: null,
          type: null,
          deptId: null,
          faultTime: null,
          faultContent: null,
          status: null,
          stopInfoId: null,
          reportUserId: null,
          dispatchTime: null,
          dispatchUserId: null,
          dealUserId: null,
          dealTime: null,
          reasonSolution: null,
          reviewUserId: null,
          reviewTime: null,
          reviewRemark: null,
          checkTime: null,
          checkUserId: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          delFlag: null,
          remark: null,
          userName: null,
          yesNo: false,
          user: null,
          repairTime: null,
        };
        this.eqpRepairRecordList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.$set(this.queryParams, 'productName', '')
        this.$set(this.queryParams, 'deptId', '')
        this.queryParams.productId = null;
        this.$set(this.queryParams, 'type', '')
        this.$set(this.queryParams, 'pageNum', 1)
        this.daterangeFaultTime = [];
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.isApproval = false
        this.open = true;
        this.openDisabled = false
        this.title = "添加故障管理信息";
      },
      /** 审批按钮操作 */
      handleApproval(row) {
        this.reset();
        this.isApproval = true
        this.openDisabled = true;
        const id = row.id || this.ids;
        getRepairFiles(id).then((response) => {
          this.form = response.data;
          this.eqpRepairRecordList = response.data.eqpRepairRecordList;
          // this.form.repairTime = dateDifference(
          //   this.form.faultTime,
          //   this.form.checkTime
          // );
          this.open = true;
          this.title = "审批故障管理信息";
        });
        getRecord(id).then((response) => {
          this.activities = response.rows;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.isApproval = false
        this.openDisabled = false;
        const id = row.id || this.ids;
        getRepairFiles(id).then((response) => {
          this.form = response.data;
          this.eqpRepairRecordList = response.data.eqpRepairRecordList;
          // this.form.repairTime = dateDifference(
          //   this.form.faultTime,
          //   this.form.checkTime
          // );
          this.open = true;
          this.title = "修改故障管理信息";
        });
        getRecord(id).then((response) => {
          this.activities = response.rows;
        });
      },

      /** 查看按钮 */
      handleView(row) {
        this.reset();
        this.isApproval = false
        this.openDisabled = true;
        const id = row.id || this.ids;
        getRepairFiles(id).then((response) => {
          this.form = response.data;
          this.eqpRepairRecordList = response.data.eqpRepairRecordList;
          // this.form.repairTime = dateDifference(
          //   this.form.faultTime,
          //   this.form.checkTime
          // );
          this.open = true;
          this.title = "查看故障信息";
        });
        getRecord(id).then((response) => {
          this.activities = response.rows;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            // this.form.eqpRepairRecordList = this.eqpRepairRecordList;
            if (this.form.id != null) {
              updateRepairFiles(this.form).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRepairFiles(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm(
          '是否确认删除故障管理信息编号为"' + ids + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delRepairInfo(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => { });
      },
      /** 故障处理记录序号 */
      rowEqpRepairRecordIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      /** 故障处理记录添加按钮操作 */
      handleAddEqpRepairRecord() {
        let obj = {};
        obj.userId = "";
        obj.nickName = "";
        obj.dealTime = "";
        obj.dealStatus = "";
        this.eqpRepairRecordList.push(obj);
      },
      /** 故障处理记录删除按钮操作 */
      handleDeleteEqpRepairRecord() {
        if (this.checkedEqpRepairRecord.length == 0) {
          this.$alert("请先选择要删除的故障处理记录数据", "提示", {
            confirmButtonText: "确定",
          });
        } else {
          this.eqpRepairRecordList.splice(
            this.checkedEqpRepairRecord[0].index - 1,
            1
          );
        }
      },
      /** 单选框选中数据 */
      handleEqpRepairRecordSelectionChange(selection) {
        if (selection.length > 1) {
          this.$refs.eqpRepairRecord.clearSelection();
          this.$refs.eqpRepairRecord.toggleRowSelection(selection.pop());
        } else {
          this.checkedEqpRepairRecord = selection;
        }
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "equipment/repairFiles/export",
          {
            ...this.queryParams,
          },
          "维修档案" + this.parseTime(new Date()) + ".xlsx"
        );
      },
    },
  };
</script>
<style>
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
</style>
